 /*
 Copyright (c) 2009 by contributors:
 
 * Google Inc. (Brad Neuberg -- http://codinginparadise.org)
 * James Hight (http://labs.zavoo.com/)
 * Richard R. Masters
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

package org.svgweb.utils; 
    
    import org.svgweb.nodes.SVGImageNode;
    import flash.utils.ByteArray;
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.DisplayObject;
    import flash.display.Loader;
    import flash.display.LoaderInfo;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;


    class ImageLoader  {

        

        var imageHref:String;
        var listeners:Array<Dynamic> ;

        var urlLoader:URLLoader;
        var bitmapData:BitmapData;

        public function new(imageHref:String){
            
            listeners = new Array();
            this.imageHref = imageHref;
        }

        public function addListener(listener:SVGImageNode):Void {
            this.listeners.push(listener);

            // started loading?
            if (null != urlLoader) {
                // loaded finished already?
                if (null != bitmapData) {
                    listeners[listeners.length-1].onImageLoaded(bitmapData);
                }
            }
            else {
                // start loading
                urlLoader = new URLLoader();
                urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
    
                urlLoader.addEventListener(Event.COMPLETE, onURLLoaderComplete);
    
                urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
               // urlLoader.addEventListener(DynamicEvent.SECURITY_ERROR, onError);
			   //TODO ASK FOR DynamicEvent.SECURITY_ERROR

                try {
                    urlLoader.load(new URLRequest(imageHref));
                } catch (e:Dynamic) {
                    for (i in 0...listeners.length) {
                        listeners[i].onImageError();
                    }
                    listener.dbg("svgweb:flash:URLLoader.load:"+e);
                }

                return;
            }
        }

        function onError(event:IOErrorEvent):Void {
            urlLoader = null;
            for (i in 0...listeners.length) {
                listeners[i].onImageError();
            }
        }

        function onURLLoaderComplete( event:Event ):Void {
            try {
                var bytes:ByteArray = cast(urlLoader.data, ByteArray);
                this.loadBytes(bytes);
            }
            catch(e:Dynamic) {
                for (i in 0...listeners.length) {
                    listeners[i].onImageError();
                }
            }
            urlLoader = null;
        }

        /**
         * Load image byte array
         * Used to support data: href.
         **/
        function loadBytes(byteArray:ByteArray):Void {
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onBytesLoaded );
            try {
                loader.loadBytes( byteArray );
            }
            catch(e:Dynamic) {
                for (i in 0...listeners.length) {
                    listeners[i].onImageError();
                }
            }
        }


        /**
         * Display image bitmap once bytes have loaded 
         * Used to support data: href.
         **/
        function onBytesLoaded( event:Event ) :Void
        {
            var content:DisplayObject = cast( event.target , LoaderInfo).content;
            bitmapData = new BitmapData( Math.round(content.width), Math.round(content.height), true, 0x00000000 );
            bitmapData.draw( content );

            for (i in 0...listeners.length) {
                listeners[i].onImageLoaded(bitmapData);
            }
            
        }
    }
